package com.gopay.common.log.logxnew.dao.impl;

import com.gopay.common.base.dao.impl.BaseDAOImpl;
import com.gopay.common.domain.log.OperLogDtl;
import com.gopay.common.log.logxnew.dao.OperLogDtlDAO;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 操作日志记录表DAO实现类
 *
 * @OperLogDtlDAOImpl.java
 * @author sh.jiao
 * @2017-5-24 上午11:09:49 www.gopay.com.cn Inc.All rights reserved.
 */
@Repository("operLogDtlDAO")
public class OperLogDtlDAOImpl extends BaseDAOImpl<OperLogDtl,Long> implements OperLogDtlDAO {

    @Override
    public OperLogDtl findOperLogDtlByParams(Map<String, String> params) {
        DetachedCriteria criteria = DetachedCriteria.forClass(OperLogDtl.class);
        String isOpenUk = params.get("isOpenUK");
        params.remove("isOpenUK");
        if(params != null && params.size() > 0) {
            for(Map.Entry<String, String> entry : params.entrySet()) {
                if("operTypeCd".equals(entry.getKey())){
                    List<String> operTypeCdList = new ArrayList<>();
                    String []  arrayList = entry.getValue().split(",");
                    for(int i = 0 ;i<arrayList.length;i++){
                        operTypeCdList.add(arrayList[i]);
                    }
                    criteria.add(Restrictions.in(entry.getKey(), operTypeCdList));
                }else{
                    criteria.add(Restrictions.eq(entry.getKey(), entry.getValue()));
                }
            }
            criteria.addOrder(Order.desc("operTs")); // 按时间倒序
            List<OperLogDtl> list = this.findByCriteria(criteria);
            if(Boolean.valueOf(isOpenUk)) {
                return list.size()>2 ? list.get(2): null;
            }
            return list.size()>1 ? list.get(1): null;
        }

        return null;
    }
}
